﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace MRSite.DataAccess
{
    [Serializable]
    public class DataAccessException : ApplicationException
    {
        public DataAccessException(SerializationInfo info, StreamingContext context)
            : base(info, context) { }

        public DataAccessException(Exception exception, string connStr, string sqlText, params DbParameter[] parameters)
            : base(BuildMessage(exception.Message, connStr, sqlText, parameters), exception) { }

        private static string BuildMessage(string message, string connStr, string sqlText, DbParameter[] parameters)
        {
            var msg = new StringBuilder();

            msg.AppendFormat("{0}\r\n", message);
            msg.AppendFormat("<<Connetion String>> : {0}\r\n", connStr);
            msg.AppendFormat("<<SQL Script>> : {0}\r\n", sqlText);
            if (parameters != null && parameters.Length > 0)
            {
                msg.Append("<<SQL Parameter(s)>> : \r\n");
                foreach (var param in parameters)
                {
                    msg.AppendFormat("{0} [{1}] : {2} [{3}]\r\n",
                        param.ParameterName,
                        param.DbType,
                        param.Value,
                        param.Value == null ? "" : param.Value.GetType().ToString());
                }
            }
            return msg.ToString();
        }
    }
}
